package email

import (
	"context"
	"crypto/tls"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"gopkg.in/gomail.v2"
	"mall_frontend_api/biz/config"
	"strconv"
)

type GOMail struct {
}

func NewGOMail() *GOMail {
	return &GOMail{}
}

func (g *GOMail) SendEmail(ctx context.Context, to string, subject, body string) error {
	port, err := strconv.Atoi(config.Values.Email.Port)
	if err != nil {
		hlog.CtxErrorf(ctx, "strconv.Atoi error: %v", err)
		return err
	}
	mailClient := gomail.NewDialer(config.Values.Email.Host, port, config.Values.Email.User, config.Values.Email.Identity)
	mailClient.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	m := gomail.NewMessage()
	m.SetAddressHeader("From", config.Values.Email.User, config.Values.Email.From)
	m.SetHeader("To", to)
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", body)
	if err = mailClient.DialAndSend(m); err != nil {
		hlog.CtxErrorf(ctx, "send email error: %v", err)
		return err
	}
	return nil
}
